package com.ctrip.ec.biz.image;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by jiangzy on 2018/8/29.
 */
@Component("imageUpload")
public class OSSUpload  extends  ImageUpload{

    @Value("${endpoint}")
    private  String endpoint;

    @Value("${accessKeyId}")
    private  String accessKeyId ;//这里是你的授权KeyId

    @Value("${accessKeySecret}")
    private  String accessKeySecret;//这里是你的授权秘钥

    @Value("${bucketName}")
    private String bucketName;

    private final static Logger logger = LoggerFactory.getLogger(OSSUpload.class);
    /**
     * OSS的文件夹名
     */

    //private static String key = "http://neoyusin.oss-cn-beijing.aliyuncs.com/";

   // private  String folder="";

    public OSSUpload(){
    }



    //@Override
//    public   String  domain(){
//        return key;
//    }

    /**
     * 上传图片
     *
     * @param fileName    文件名
     * @param inputStream 流
     */
    @Override
    public String upload(String fileName, InputStream inputStream) {
        /**
         * 创建OSS客户端
         */
        String folder = getFolder();

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        try {

            ossClient.putObject(new PutObjectRequest(bucketName, folder + fileName, inputStream));
            return folder + fileName;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            throw e;
          //  System.err.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }

    }

    private  String getFolder(){
        String folder = "upload/";
        //ImageFileUpload.uploadFile(file.getBytes(), filePath, fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date now = new Date(System.currentTimeMillis());
        String yearMonth = sdf.format(now);
        folder += sdf.format(now) + "/";
        return folder;
    }


    /**
     * 多图上传
     */
//    public String[] uploadBatch(String[] fileNames, InputStream[] inputStreams) {
//        /**
//         * 创建OSS客户端
//         */
//        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//        try {
//            ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue(
//                    Arrays.asList(fileNames));
//            ConcurrentLinkedQueue<InputStream> streamConcurrentLinkedQueue = new ConcurrentLinkedQueue<>(
//                    Arrays.asList(inputStreams));
//            Iterator<InputStream> inputStreamss = streamConcurrentLinkedQueue.iterator();
//            ConcurrentLinkedQueue c = new ConcurrentLinkedQueue();
//            for (Iterator<String> iterator = concurrentLinkedQueue.iterator();
//                 iterator.hasNext() && inputStreamss.hasNext(); ) {
//                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//                String[] names = iterator.next().split("[.]");
//                String name = uuid + "." + names[names.length - 1];
//                ossClient.putObject(new PutObjectRequest(bucketName, folder + name, inputStreamss.next()));
//                c.add(key + folder + name);
//            }
//            return (String[]) c.toArray(new String[0]);
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.err.println(e.getMessage());
//        } finally {
//            ossClient.shutdown();
//        }
//        return null;
//    }


    /**
     * 删除图片 警告：在没有调用其他方法的情况下，请调用closeClient方法
     *
     * @param url URL全路径
     */
    public void delete(String url) {
        //String folder = getFolder();

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        if (url == null || "".equals(url)) {
            return;
        }
        String[] paths = url.split("[.]");
        /**
         * 文件夹是否存在
         */
//        if (!ossClient.doesObjectExist(bucketName, folder)) {
//            ossClient.putObject(bucketName, folder, new ByteArrayInputStream(new byte[0]));
//        }
//        String[] name = paths[paths.length - 2].split("[/]");
        /**
         * 对象是否存在
         */
        if (ossClient.doesObjectExist(bucketName, url)) {
            /**
             * 删除存在对象
             */
            ossClient.deleteObject(bucketName, url);
        }
        ossClient.shutdown();
    }


}